#include "fileio.h"

// Static config variable
// Accessed through get-functions
static serverconfp config;

serverconfp initConf(void){
	FILE *cFile;

	config = (serverconfp) malloc(sizeof (serverconf));

	cFile = fopen("webserver.cfg", "r");
	if ( cFile == NULL) {
		printf("Could not open config file");
		exit(1);
	}
	
	fscanf(cFile, "HTTPPORT=%s\nADMINPORT=%s\nWEBFOLDER=%s\nPASSWORD=%s\nLOGFILE=%s",
		config->http_port, config->admin_port, config->http_folder, config->admin_password, config->log_file);

	fclose(cFile);

	return config;
}

int isModifiedSince(char *filename, char *htime){
	char weekday[5], mon[5];
	time_t rawtime;
	char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
	struct tm *timeinfo;
	struct stat buf;
	double res;
	int i;

	if ( !strcmp(htime, "") )
		return 1;

	time(&rawtime);
	timeinfo = localtime(&rawtime);

	sscanf(htime, "%s %d %s %d %d:%d:%d", weekday, &(timeinfo->tm_mday), mon, &(timeinfo->tm_year), &(timeinfo->tm_hour), &(timeinfo->tm_min), &(timeinfo->tm_sec));

	for (i = 0; i < 12; i++){
		if (!strcmp(mon, months[i])){
			timeinfo->tm_mon = (i+1);
			break;
		}
	}

	timeinfo->tm_year -= 1900;
	timeinfo->tm_mon -= 1;
	timeinfo->tm_isdst = -1;

	rawtime = mktime(timeinfo);

	stat(filename, &buf);

	res = difftime(rawtime , buf.st_mtime );

	if (res >= 0){
		return 0;
	} else {
		return 1;
	}

}

char *getHTTPPort(){
	return config->http_port;
}

char *getAdminPort(){
	return config->admin_port;
}

char *getHTTPFolder(){
	return config->http_folder;
}

char *getAdminPassword(){
	return config->admin_password;
}

char *getLogFileName(){
	return config->log_file;
}